import { DirectiveBinding } from 'vue';

import { usePermissionStore } from '@/store';

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding;

  const { permissions } = usePermissionStore();

  if (Array.isArray(value) && value.length) {
    const hasPermission = value.find((key) => permissions.includes(key));

    if (!hasPermission && el) {
      if (el.parentElement?.className === 't-space-item') {
        el.parentElement.remove();
      } else {
        el.remove();
      }
    }
  } else {
    throw new Error(`need permission! Like v-permission="['xxx:xxx:xxx','ooo:ooo:ooo']"`);
  }
}
export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
};
